package info.emamian.droplet.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;

public class DynamoDbClientFactory {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(DynamoDbClientFactory.class);

	private static int clientCount = 0;
	private static int mapperCount = 0;
	private static ClasspathPropertiesFileCredentialsProvider credentialsProvider = new ClasspathPropertiesFileCredentialsProvider(
			"AwsCredentials.properties");

	public static AmazonDynamoDBClient getClientInstance() {
		AmazonDynamoDBClient client = new AmazonDynamoDBClient(
				credentialsProvider);
		LOGGER.info(client.getServiceName());

		// local or actual region
		client.setEndpoint("http://localhost:8000", "dynamodb", "local");
		// client.setRegion(Region.getRegion(Regions.US_WEST_2));

		clientCount++;
		LOGGER.info("Client created, count:{}", clientCount);
		LOGGER.info("Listing tables: " + client.listTables());
		return client;
	}

	/**
	 * Creates a mapper ( and a client for it) and returns the usable mapper.
	 * 
	 * @return
	 */
	public static DynamoDBMapper getDBMapperInstance() {
		DynamoDBMapperConfig mapperConfig = new DynamoDBMapperConfig(
				DynamoDBMapperConfig.SaveBehavior.CLOBBER,
				DynamoDBMapperConfig.ConsistentReads.CONSISTENT, null, // TableNameOverride
																		// -
																		// leaving
																		// this
																		// at
																		// default
																		// setting
				DynamoDBMapperConfig.PaginationLoadingStrategy.EAGER_LOADING);

		DynamoDBMapper mapper = new DynamoDBMapper(getClientInstance(),
				mapperConfig, credentialsProvider);
		mapperCount++;
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Mapper created, count:{}", mapperCount);
		}
		return mapper;
	}

	public static int getClientCount() {
		return clientCount;
	}

	public static void setClientCount(final int clientCount) {
		DynamoDbClientFactory.clientCount = clientCount;
	}

	public static int getMapperCount() {
		return mapperCount;
	}

	public static void setMapperCount(final int mapperCount) {
		DynamoDbClientFactory.mapperCount = mapperCount;
	}

}
